package com.grey_zoo.lottery;

import ZhongXinFenPai.ChangeActivityEvent;
import ZhongXinFenPai.TCallback;
import ZhongXinFenPai.TEvent;
import ZhongXinFenPai.TIntent;
import ZhongXinFenPai.TObserver;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.grey_zoo.lottery.eventhandler.BombEventHandler;
import com.grey_zoo.lottery.eventhandler.ChnageUIEventHandler;
import com.grey_zoo.lottery.eventhandler.ImageLoaderEventHandler;
import com.grey_zoo.lottery.eventhandler.TecentEventHandler;
import com.grey_zoo.lottery.global.GlobalValue;
import com.grey_zoo.lottery.presenter.TecentEventManager.LoginListener;
import com.grey_zoo.lottery.util.ConfigSharePreferenceUtils;
import com.grey_zoo.lottery.util.MyUtils;
import com.grey_zoo.lottery.util.PromptManager;
import com.grey_zoo.lottery.view.fragment.HomeFragment;
import com.grey_zoo.lottery.view.fragment.NoUserFragment;
import com.grey_zoo.lottery.view.manager.BottomManager;
import com.grey_zoo.lottery.view.manager.MiddleManager;
import com.grey_zoo.lottery.view.manager.TitleManager;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.CanvasTransformer;
import com.tencent.tauth.Tencent;
import com.grey_zoo.lottery.eventhandler.BombEventHandler;

public class MainActivity extends FragmentActivity implements OnClickListener, TObserver {

	private BombEventHandler itsBombEventHandler;
	private ImageView icon_menu;
	private ImageView icon_home;
	private ImageView channel6;
	private ImageView channel4;
	private ImageView channel2;
	boolean kai = true;

	private RelativeLayout level1;
	private RelativeLayout level2;
	private RelativeLayout level3;

	private RelativeLayout youku;
	/**
	 * 判断 第3级菜单是否显示 true 为显示
	 */
	private boolean isLevel3Show = true;
	/**
	 * 判断 第2级菜单是否显示 true 为显示
	 */
	private boolean isLevel2Show = true;
	/**
	 * 判断 第1级菜单是否显示 true 为显示
	 */
	private boolean isLevel1show = true;

	public static int mScreenWidth, mScreenHeight;

	private static Interpolator interp = new Interpolator() {
		@Override
		public float getInterpolation(float t) {
			t -= 1.0f;
			return t * t * t + 1.0f;
		}
	};

	// sharepareference
	private ConfigSharePreferenceUtils sharePreferenceUtils;
	// fragment缩放动画
	CanvasTransformer mTransformer;
	// 中间的布局
	private LinearLayout ll_middle;
	// Title的布局
	private RelativeLayout rl_title;
	// Buttom的布局
	private RelativeLayout rl_buttom;
	// OnResume的时候判断是否为第一次加载
	private boolean hasLoad = false;

	private SlidingMenu slidingMenu = null;

	/*
	 * public Handler handler =new Handler(){
	 * 
	 * public void handleMessage(Message message){ switch(message.what){
	 * 
	 * 
	 * 
	 * 
	 * }
	 * 
	 * 
	 * }
	 * 
	 * };
	 */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.il_main);
		// initScreenSize();
		registerMainEvent();
		initSlieMenu();
		//ImageLoaderEventHand(0, null, null);
		// initImageLoader();

		// 进行Bmob的初始化
		//Bmob.initialize(MainActivity.this, GlobalValue.BMOBKEY);

		// BmobInstallation.getCurrentInstallation(this).save();
		// 启动推送服务
		// BmobPush.startWork(this, GlobalValue.BMOBKEY);

		// 初始化（获取对象与进行初始布局）

		init();
		initmenu();
		BombEventHandler.BombInitEventHandler(0);
		ImageLoaderEventHandler.ImageLoaderInitEventHand(0);
		initSP();

	}

	public void initSP() {
		ConfigSharePreferenceUtils sharePreferenceUtil = new ConfigSharePreferenceUtils(this);
		GlobalValue.sharePreferenceUtil = sharePreferenceUtil;

	}

	/*public static void BombEventHandler(int flag,int chongzhimoney,int buymoney) {
	
		BombEvent bomb = new BombEvent();
		bomb.flag = flag;
		bomb.chongzhimoney=chongzhimoney;
		bomb.buymoney=buymoney;
		TIntent.getInstance().dispatch(bomb, null);
	
	}*/

	/*
	 * public static int BombEventMoneyHandler(int flag) {
	 * 
	 * BombCallBack bombcallback = new BombCallBack();
	 * 
	 * BombEvent bomb = new BombEvent(); bomb.flag = flag;
	 * TIntent.getInstance().dispatch(bomb, bombcallback);
	 * 
	 * if (bombcallback.money == 0) {
	 * 
	 * PromptManager.showProgressDialog(GlobalValue.activity);
	 * 
	 * 
	 * } else { PromptManager.closeProgressDialog(); return bombcallback.money;
	 * } }
	 */

	public void registerMainEvent() {

		TIntent.getInstance().registerEvent(ChangeActivityEvent.class, this);

	}

	/*public static void ImageLoaderEventHand(int flag, ImageView imageview,
			String url) {
	
		ImageLoaderEvent imageevent = new ImageLoaderEvent();
		imageevent.flat = flag;
		imageevent.imageview = imageview;
		imageevent.url = url;
	
		TIntent.getInstance().dispatch(imageevent, null);
	
	}*/

	/*
	 * public void initImageLoader() { ImageLoaderConfiguration config = new
	 * ImageLoaderConfiguration.Builder( getApplicationContext()).build();
	 * 
	 * ImageLoader.getInstance().init(config);
	 * 
	 * GlobalValue.imageLoader = ImageLoader.getInstance();
	 * 
	 * }
	 */

	public void initmenu() {
		youku = (RelativeLayout) findViewById(R.id.youku);
		icon_home = (ImageView) youku.findViewById(R.id.icon_home);
		icon_menu = (ImageView) youku.findViewById(R.id.icon_menu);

		channel4 = (ImageView) youku.findViewById(R.id.channel4);
		channel2 = (ImageView) youku.findViewById(R.id.channel2);
		channel6 = (ImageView) youku.findViewById(R.id.channel6);
		level1 = (RelativeLayout) youku.findViewById(R.id.level1);
		level2 = (RelativeLayout) youku.findViewById(R.id.level2);
		level3 = (RelativeLayout) youku.findViewById(R.id.level3);

		icon_home.setOnClickListener(this);

		icon_menu.setOnClickListener(this);
		channel2.setOnClickListener(this);
		channel4.setOnClickListener(this);
		channel6.setOnClickListener(this);

	}

	/*
	 * private void initScreenSize() { DisplayMetrics dm =
	 * getResources().getDisplayMetrics();// 获取屏幕密度 mScreenWidth =
	 * dm.widthPixels; mScreenHeight = dm.heightPixels; }
	 */

	private void init() {

		/*
		 * 设置Context
		 */
		//GlobalValue.context = this;

		/*
		 * 实例化Tencent
		 */
		TecentEventHandler.CreateTecentInstance(0);

		/*
		 * Activity初始化
		 */
		GlobalValue.activity = this;

		// 登录数据
		//final UserEngin engin = new UserEngin();

		PromptManager.showProgressDialog2(this);

		// 获取main中的ViewGroup
		rl_title = (RelativeLayout) findViewById(R.id.iv_mian_title);
		rl_buttom = (RelativeLayout) findViewById(R.id.iv_mian_buttom);
		ll_middle = (LinearLayout) findViewById(R.id.iv_main_middle);
		// 设置单例的
		TitleManager.getInstance().setView(rl_title);
		BottomManager.getInstance().setView(rl_buttom);

		// TitleManager.getInstance().init(this);
		// ButtomManager.getInstance().init(this);

		// //展示普通的title与buttom
		// TitleManager.getInstance().showCommom();
		// ButtomManager.getInstance().showCommom();

		// 展示主页
		// MainUIFactory factory=new MainUIFactory();
		// BaseUI baseUI=MainUIFactory.getInstance("hall",this);

		// 添加到manager
		MiddleManager.getInstance().init(ll_middle);
		// MiddleManager.getInstance().changeUI("home", null);
		ChnageUIEventHandler.SwitchUI("home", null);

		/*
		 * 初始化登录数据
		 */
		/*engin.tryLogin(new LoginListener() {
		
			@Override
			public void onSucceed() {
				// TODO 自动生成的方法存根
				Toast.makeText(MainActivity.this, "登陆成功~~", Toast.LENGTH_SHORT)
						.show();
				MiddleManager.getInstance().NoticeAll();
				TitleManager.getInstance().setLoginText(GlobalValue.username);
		
				//engin.checkAndGetBmobMoney();
				BombEventHandler.BombCheckMoneyEventHandler(1);
				initSlideMenuFragment();
				// System.out.println(""+GlobalValue.userMoney);
				PromptManager.closeProgressDialog();
			}
		
			@Override
			public void onFail() {
				// TODO 自动生成的方法存根
				Toast.makeText(MainActivity.this, "登陆失败~~,请稍后再试~~",
						Toast.LENGTH_SHORT).show();
				PromptManager.closeProgressDialog();
			}
		});*/

		TecentEventHandler.TryLoginEventHand(1, new LoginListener() {

			@Override
			public void onSucceed() {
				// TODO 自动生成的方法存根
				Toast.makeText(MainActivity.this, "登陆成功~~", Toast.LENGTH_SHORT).show();
				MiddleManager.getInstance().NoticeAll();
				TitleManager.getInstance().setLoginText(GlobalValue.username);

				//engin.checkAndGetBmobMoney();
				BombEventHandler.BombCheckMoneyEventHandler(1);
				initSlideMenuFragment();
				// System.out.println(""+GlobalValue.userMoney);
				PromptManager.closeProgressDialog();
			}

			@Override
			public void onFail() {
				// TODO 自动生成的方法存根
				Toast.makeText(MainActivity.this, "登陆失败~~,请稍后再试~~", Toast.LENGTH_SHORT).show();
				PromptManager.closeProgressDialog();
			}
		});
	}

	public void initSlieMenu() {
		slidingMenu = new SlidingMenu(this);
		slidingMenu.setMode(SlidingMenu.LEFT);
		slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN); // 触摸边界拖出菜单
		slidingMenu.setMenu(R.layout.menu_laft);
		// slidingMenu.setSecondaryMenu(R.layout.slidingmenu_right);
		slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		// 将抽屉菜单与主页面关联起来
		slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);

		mTransformer = new CanvasTransformer() {

			@Override
			public void transformCanvas(Canvas canvas, float percentOpen) {
				canvas.translate(0, canvas.getHeight() * (1 - interp.getInterpolation(percentOpen)));
			}
		};

		slidingMenu.setBehindCanvasTransformer(mTransformer);
	}

	public static void initSlideMenuFragment() {

		// 创建fragment
		HomeFragment menuFragment = new HomeFragment();
		// 获取fragment的管理者
		GlobalValue.activity.getSupportFragmentManager()
				// 开启事物
				.beginTransaction()
				// 替换
				.replace(R.id.smenu_left, menuFragment, "Menu")
				// 提交
				.commit();
	}

	public static void initNoUserSlideMenuFragment() {

		// 创建fragment
		NoUserFragment nousermenuFragment = new NoUserFragment();
		// 获取fragment的管理者
		GlobalValue.activity.getSupportFragmentManager()
				// 开启事物
				.beginTransaction()
				// 替换
				.replace(R.id.smenu_left, nousermenuFragment, "Menu")
				// 提交
				.commit();
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
	 * menu; this adds items to the action bar if it is present.
	 * getMenuInflater().inflate(R.menu.main, menu); return true; }
	 */
	@Override
	protected void onStop() {

		super.onStop();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		JPushInterface.onPause(this);
	}

	@Override
	protected void onResume() {
		// TODO 自动生成的方法存根
		JPushInterface.onResume(this);
		/*
		 * Intent intent = new Intent();
		 * intent.setAction("cn.bmob.push.action.MESSAGE");
		 * sendBroadcast(intent); Toast.makeText(getApplicationContext(),
		 * "发送广播成功", Toast.LENGTH_SHORT).show();
		 */

		if (hasLoad) {
			MiddleManager.getInstance().onResume();
		}
		hasLoad = true;
		super.onResume();
	}

	// 实现返回的方法
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO 自动生成的方法存根
		// return super.onKeyDown(keyCode, event);

		if (keyCode == KeyEvent.KEYCODE_MENU) {

			if (kai == true) {
				youku.setVisibility(View.VISIBLE);
				kai = false;

			} else {
				changeLevel1State();
				return super.onKeyDown(keyCode, event);
			}
		}

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MiddleManager.getInstance().BackKey();
			return true;

		} else {

			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		GlobalValue.tencent.onActivityResult(requestCode, resultCode, data);
	}

	// slidingMenu.setBehindScrollScale(0.5f);

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.icon_menu: // 处理 menu 图标的点击事件
			// 如果第3级菜单是显示状态，那么将其隐藏
			if (isLevel3Show) {
				// 隐藏 第3级菜单
				MyUtils.startAnimOut(level3);
			} else {
				// 如果第3级菜单是隐藏状态，那么将其显示
				MyUtils.startAnimIn(level3);
			}

			isLevel3Show = !isLevel3Show;

			break;
		case R.id.icon_home: // 处理 home 图标 的点击事件
			// 如果第2级菜单是显示状态，那么就隐藏，2，3级菜单
			if (isLevel2Show) {
				MyUtils.startAnimOut(level2);
				isLevel2Show = false;

				if (isLevel3Show) { // 如果此时，第3级菜单也显示，那也将其隐藏
					MyUtils.startAnimOut(level3, 200);
					isLevel3Show = false;
				}

			} else {
				// 如果第2级菜单是隐藏状态，那么就显示2级菜单
				MyUtils.startAnimIn(level2);
				isLevel2Show = true;
			}

			break;

		case R.id.channel4:
			//	MiddleManager.getInstance().changeUI("hall", null);
			ChnageUIEventHandler.SwitchUI("hall", null);
			break;
		case R.id.channel2:
			//MiddleManager.getInstance().changeUI("userdata", null);
			ChnageUIEventHandler.SwitchUI("userdata", null);
			break;

		case R.id.channel6:
			ChnageUIEventHandler.SwitchUI("home", null);
			//MiddleManager.getInstance().changeUI("home", null);
			break;
		}
	}

	private void changeLevel1State() {
		// 如果第1级菜单是显示状态，那么就隐藏 1，2，3级菜单
		// youku.setVisibility(View.VISIBLE);

		if (isLevel1show) {
			MyUtils.startAnimOut(level1);
			isLevel1show = false;

			if (isLevel2Show) { // 判断2级菜单是否显示
				MyUtils.startAnimOut(level2, 100);
				isLevel2Show = false;
				if (isLevel3Show) { // 判断3级菜单是否显示
					MyUtils.startAnimOut(level3, 200);
					isLevel3Show = false;
				}
			}

		} else {
			// 如果第1级菜单是隐藏状态，那么就显示 1，2级菜单
			youku.setVisibility(View.VISIBLE);
			MyUtils.startAnimIn(level1);
			isLevel1show = true;

			MyUtils.startAnimIn(level2, 200);
			isLevel2Show = true;

			MyUtils.startAnimIn(level3, 200);
			isLevel3Show = true;
		}

	}

	@Override
	public void onEvent(TEvent event, TCallback callback) throws NoSuchMethodException, Exception, Exception {
		// TODO Auto-generated method stub

		final ChangeActivityEvent changeevent = (ChangeActivityEvent) event;
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				MiddleManager.getInstance().changeUI(changeevent.to, changeevent.bundle);
			}
		});

	}

}
